import React, { useState, useCallback, useEffect, useMemo, useRef } from "react";
import { Form } from "antd";
import { cloneDeep } from "lodash";
import { customTrimFunc } from "@/utils/utils.jsx";
import { useSessionStorageState } from "ahooks";

/**
 *
 * @param {*} tableKey,
 * @param {*} keepSelected, 在翻页时，是否保留选中
 * @param {*} columns,
 * @param {*} tableRequest,
 * @param {*} autoFetch,
 * @param {*} searchSpan,
 * @param {*} hasPagination,
 * @param {*} hasQuickSearch,
 * @param {*} pageSize,分页默认值
 * @param {*} pageSizeOptions,分页
 * @param {*} beforeQuerySearch,
 * @param {*} resetSourceData
 * @param {*} afterFetch 请求后的回调函数 (dataSource)=>void
 * @param {*} nextPipeline
 * @param {*} footerDataSource
 * @param {*} nextPipeline 其它拓展功能，如排序  nextPipeline = (pipeline)=> pipeline.use(features.sort({ columnKey: 'id', order: 'descend' }));
 * @param {*} getRowsByIds 默认根据咯一rowKey返回行数据
 * @param {*} selectionChange (selectedRowKeys,selectedRows)=> void
 * @param {*} hasColsSetting 按钮栏右侧设置列功能
 * @param {*} hasToggleSearchForm 操作栏上方 收起/展开 搜索表单 的功能
 * @returns
 */
export const useTableConfig = ({
	className,
	tableKey,
	rowKey = "id",
	keepSelected = false,
	columns,
	tableRequest,
	autoFetch,
	searchSpan,
	hasPagination,
	hasQuickSearch,
	beforeReset,
	beforeQuerySearch,
	resetSourceData,
	afterFetch,
	nextPipeline,
	footerDataSource,
	getRowsByIds,
	pageSize,
	pageSizeOptions,
	selectionChange,
	hasColsSetting,
	hasToggleSearchForm,
	columnResize,
	sortProps
}) => {
	const [form] = Form.useForm();
	const [query, setQuery] = useState({});
	const updateSearchQuery = useCallback(v => {
		setQuery(cloneDeep(v));
	}, []);
	// 组件 pagination 的 属性
	const initPagination = {
		current: 1, //当前 页码 // 从1开始
		total: 0, //数据总量
		pageSize: pageSize ? pageSize : 10, //每页条数
		showQuickJumper: true,
		pageSizeOptions: pageSizeOptions ? pageSizeOptions : [10, 50, 100, 200, 500]
	};
	//pagination组件入参数据
	const [pagination, setPagination] = useState({ ...initPagination });
	const updatePaginationParams = useCallback(v => {
		setPagination(cloneDeep(v));
	}, []);

	const stagePageSize = useRef(0);

	/** 数据源 */
	const [dataSource, setDataSource] = useState([]);
	const updateDataSource = useCallback(v => {
		if (Array.isArray(v)) {
			setDataSource(cloneDeep(v));
		} else if (typeof v === "function") {
			setDataSource(v);
		} else {
			setDataSource([]);
		}
	}, []);

	/** 将 onChange 抛炪的数据存储在外部 */
	const [selectedKeys, setSelectedKeys] = useState([]);
	const [selectedRows, setSelectedRows] = useState([]);
	//翻页保留的数据 1  [...rows]
	const [selectedPageRows, setSelectedPageRows] = useState([]);
	//翻页保留的数据 2  [...rows]
	const selectedAllPagesRows = useRef([]);
	useEffect(() => {
		const arr = [];
		selectedPageRows.forEach(row => {
			if (!arr.find(e => e[rowKey] == row[rowKey])) arr.push(row);
		});
		selectedAllPagesRows.current = arr;
		selectionChange &&
			selectionChange(
				arr.map(e => e[rowKey]),
				arr
			);
	}, [selectedPageRows]);
	const addSelectedPageRows = useCallback(
		(newRows, action) => {
			console.log(action, "actionssssssssssss");
			// TODO && newRows.length 加了长度判断，会导致最后一个去除选中的时候，不会触发selectionChange
			if (newRows) {
				setSelectedPageRows(pre => {
					const __pre = cloneDeep(pre);
					newRows.forEach(row => {
						if (!__pre.find(e => e[rowKey] == row[rowKey])) __pre.push(row);
					});
					return __pre;
				});
			}
		},
		[pagination]
	);

	const deleteSelectedPageRows = useCallback(
		(keys, action) => {
			console.log(action, "action");
			console.log(keys, "keys");
			// TODO && newRows.length 加了长度判断，会导致最后一个去除选中的时候，不会触发selectionChange
			if (action == "uncheck") {
				if (keys) {
					setSelectedPageRows(pre => {
						const __pre = cloneDeep(pre);
						return __pre.filter(x => !keys.some(i => i == x[rowKey]));
					});
				}
			}
			if (action == "uncheck-all") {
				const allKeys = dataSource.map(x => x[rowKey]);
				console.log(allKeys, "allKeys");
				setSelectedPageRows(pre => {
					const __pre = cloneDeep(pre);
					let otherPageSelectList = __pre.filter(x => !allKeys.some(i => i == x[rowKey]));
					return otherPageSelectList;
				});
			}
		},
		[pagination]
	);
	// 根据selectedPageRows回显页面选中行
	const setTableSelectByPageRows = useCallback(
		d => {
			if (d && d.length) {
				const tempKeys = [];
				d.forEach(item => {
					selectedPageRows.forEach(row => {
						const f = row[rowKey] === item[rowKey];
						if (f) {
							tempKeys.push(item[rowKey]);
						}
					});
				});

				setTimeout(() => {
					RefTable?.current?.setTableSelect?.(tempKeys);
				}, 10);
			} else {
				setSelectedPageRows([]);
			}
		},
		[selectedPageRows]
	);
	/**
   * key 触发本次状态改变的表格行的 key
    action: 交互行为  check uncheck uncheck-all check-all
   */
	const onChange = useCallback(
		(keys, rows, key, action) => {
			console.log(key, "key");
			console.log(keys, "keysssssssssssssss");
			if (keepSelected) {
				if (action == "uncheck" || action == "uncheck-all") {
					deleteSelectedPageRows(key ? [key] : keys, action);
				} else {
					addSelectedPageRows(rows, action);
				}
			} else {
				setSelectedKeys(keys);
				setSelectedRows(rows);
				selectionChange && selectionChange(keys, rows);
			}
		},
		[pagination]
	);
	/** 清空勾选数据 */
	const RefTable = useRef(null);
	const clearTableSelected = useCallback(() => {
		setSelectedPageRows([]);
		// 清空勾选的外部数据
		const defaultSelected = Array.isArray(selectedRows) ? [] : null;
		setSelectedKeys(defaultSelected);
		setSelectedRows(defaultSelected);
		// 清空勾选的内部数据与UI（useMultiSelect）
		RefTable?.current?.clearTableSelected?.();
	}, [setSelectedKeys, setSelectedRows, selectedRows]);

	/** 更新数据 */
	const saveData = useCallback(
		(d, action) => {
			if (typeof afterFetch === "function") afterFetch(d);
			if (typeof resetSourceData === "function") d = resetSourceData(d);
			updateDataSource(d);
			// 回显数据
			if (action == "pageChange" && keepSelected) setTableSelectByPageRows(d);
		},
		[resetSourceData, afterFetch, setTableSelectByPageRows]
	);
	// api分页入参
	const getQueryPagination = useCallback(
		p => {
			p = p || pagination;
			return {
				pageNum: p.current,
				pageSize: p.pageSize, //当前 页码 // 从1开始
				total: p.total //数据总量
			};
		},
		[pagination]
	);

	/** 处理form数据中的时间参数（Moment类型） */
	const getFormValueWithTime = useCallback(
		val => {
			Object.keys(val).forEach(key => {
				const v = val[key];
				if (Array.isArray(v) && v.length === 2 && v[0]._isAMomentObject === true) {
					let keys = null;
					columns.forEach(col => {
						if (col.code == key || col?.search?.code == key) {
							keys = col.search.keys;
						}
						if (col?.search?.group) {
							const findSearchItem = col.search.group.find(colChild => colChild.code == key);
							if (findSearchItem) keys = findSearchItem.keys;
						}
					});
					if (keys) {
						val[keys[0]] = v[0].format("YYYY-MM-DD HH:mm:ss");
						val[keys[1]] = v[1].format("YYYY-MM-DD HH:mm:ss");
						delete val[key];
					} else {
						console.error(
							"查询条件 " +
								key +
								" 的值是一个 Moment 时间数组，此时默认是查询一个时间满园，请在columns.search.keys:[timeStart,timeEnd] 作为真正的查询参数"
						);
					}
				}
			});
			return customTrimFunc(val);
		},
		[columns]
	);
	/**
	 * 获取列表数据
	 * @param {*} customQuery 搜索条件
	 * @param {*} customPagination 分页条件
	 * @param {*} action 搜索触发的前置行为:  search查询 / reset重置 / pageChange分页-翻页 / sizeChange分页-改变每页条数
	 */
	const fetchList = useCallback(
		async (customQuery, customPagination, action = "search") => {
			if (action == "sizeChange") {
				stagePageSize.current = customPagination?.pageSize;
			}
			if (!((action == "search" || action == "pageChange") && keepSelected)) clearTableSelected();
			let API_DATA = { ...getFormValueWithTime(customQuery || query), ...(customPagination || getQueryPagination()) };
			if (stagePageSize.current) {
				API_DATA.pageSize = stagePageSize.current;
			}
			// 调用接口前处理搜索数据
			if (typeof beforeQuerySearch === "function") {
				API_DATA = await beforeQuerySearch({ API_DATA });
			}
			// 中文逗号转英文
			Object.keys(API_DATA).forEach(key => {
				if (typeof API_DATA[key] === "string") API_DATA[key] = API_DATA[key].replace(/，/g, ",");
			});
			tableRequest(API_DATA)
				.then(res => {
					const { code, success, data } = res;
					if (success) {
						if (hasPagination !== false) {
							const { records, total, size, current, pages } = data;

							saveData(records, action);

							updatePaginationParams({
								...pagination,
								current: current, //当前 页码 // 从1开始
								total: total, //数据总量
								pageSize: size //每页条数
							});
						} else {
							const records = Array.isArray(data)
								? data
								: data && Array.isArray(data.data)
									? data.data
									: data && Array.isArray(data.records)
										? data.records
										: data && Array.isArray(data.list)
											? data.list
											: [];
							saveData(records, action);
						}
					}
				})
				.catch(err => {
					updateDataSource([]);
					console.error("获取数据异常", err);
				});
		},
		[query, beforeQuerySearch, tableRequest, hasPagination, saveData, updatePaginationParams, pagination, getFormValueWithTime]
	);
	useEffect(() => {
		if (autoFetch && tableKey) {
			const formData = form.getFieldsValue();
			updateSearchQuery(formData);
			fetchList(formData, { pageNum: initPagination.current, pageSize: initPagination.pageSize });
		}
	}, [tableKey]);

	const paginationProps = {
		pagination,
		/**
		 *
		 * @param {*} current 改变后的页码
		 * @param {*} pageSize 每页条数
		 */
		handleChange(current, pageSize) {
			const __P = {
				...pagination,
				current, //当前 页码 // 从1开始
				pageSize //每页条数
			};

			setPagination({ ...__P });
			fetchList(null, { ...getQueryPagination(__P) }, pageSize == pagination.pageSize ? "pageChange" : "sizeChange");
		}
	};
	const searchSimpleTableProps = {
		className,
		ref: RefTable,
		form,
		fetchList,
		dataSource,
		beforeReset,
		updateSearchQuery,
		//////////////
		tableKey,
		rowKey,
		columns,
		searchSpan,
		hasPagination,
		paginationProps,
		hasQuickSearch,
		footerDataSource,
		nextPipeline,
		getRowsByIds,
		onChange,
		hasColsSetting,
		hasToggleSearchForm,
		columnResize,
		sortProps
	};

	return {
		RefTable,
		selectedKeys, // 多选返回key[], 单选返回 key
		selectedRows, // 多选返回row[], 单选返回 row
		selectedAllPagesRows, // 翻页保留的数据
		clearTableSelected,
		fetchList,
		dataSource,
		form,
		query,
		pagination,
		updateDataSource,
		updateSearchQuery,
		updatePaginationParams,
		searchSimpleTableProps,
		getFormValueWithTime
	};
};
